# -*- coding: utf-8 -*-

from flask import redirect, jsonify

from face_recognition.utils import config_utils
from face_recognition import app
from flask import request, session
from face_recognition.models.user_info import UserInfo


@app.route('/face_recognition/login', methods=['POST'])
def login():
	"""
	登录系统：目前只有管理能登录系统，管理员用户密码在config.properties文件里
	:return:
	"""
	if request.headers['Content-Type'] == 'application/json':
		data = request.get_json()
		admin_name = config_utils.get_property_with_name("admin_user", "name")
		admin_pwd = config_utils.get_property_with_name("admin_user", "password")
		if  data["email"] == admin_name:
			if data["password"] == admin_pwd:
				# 登录成功
				user = UserInfo()
				user.email = data["email"]
				user.id = UserInfo.create_id()
				user.username = data["email"]
				session["login_user"] = user.to_json()
				result = {"status": "success", "message": "登录成功！"}
			else:
				result = {"status": "error", "message": "用户密码不正确！"}
		else:
			result = {"status": "error", "message": "用户名不正确！"}
		return jsonify(result)
	else:
		print("请求的数据格式不正确，要求application/json")
		return redirect('face_recognition/login.html')


@app.route('/face_recognition/logout', methods=['GET'])
def logout():
	"""
	登出系统
	:return:
	"""
	session["login_user"] = None
	result = {"status": "success", "message": "登出成功！"}
	return jsonify(result)


@app.route('/face_recognition/whoami', methods=['GET'])
def who_am_i():
	"""
	获取登录用户名
	:return:
	"""
	if not session.get('login_user'):
		result = {"status": "error", "message": "用户未登录系统！"}
	else:
		result = {"status": "success", "message": "登录成功！", "user": session.get('login_user')}
	return jsonify(result)
